<template>
  <div class="full-container">
    <el-card style="height: 100%; width: 100%">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="addUser">
            <i class="el-icon iconfont icon-zhuanshukefu"></i>
            <span>新增用户</span>
          </el-button>
          <el-button type="primary" @click="loginShop">
            <i class="el-icon iconfont icon-zhuanshukefu"></i>
            <span>登录店铺</span>
          </el-button>
          <el-button type="primary" @click="importShop">
            <i class="el-icon iconfont icon-zhuanshukefu"></i>
            <span>导入店铺</span>
          </el-button>
          <el-button type="primary" @click="downTemplate">
            <i class="el-icon iconfont icon-zhuanshukefu"></i>
            <span>模板下载</span>
          </el-button>
          <el-button type="success" @click="getSelectedData">
            <i class="el-icon-check"></i>
            <span>获取选中数据</span>
          </el-button>
          <el-button type="success" @click="test">
            <i class="el-icon-check"></i>
            <span>测试IP代理请求</span>
          </el-button>
          <el-button type="success" @click="test1">
            <i class="el-icon-check"></i>
            <span>测试打开窗口新增邮费设置</span>
          </el-button>
        </div>
      </template>
      <vxe-table
        align="center"
        :size="configStore.getTableSize"
        ref="tableRef"
        border
        :row-config="{ isHover: true }"
        :data="tableData"
        :checkbox-config="{ labelField: 'name', highlight: true }"
      >
        <vxe-column type="checkbox" title="旺旺名称" align="left"></vxe-column>
        <vxe-column field="shop_name" title="店铺名称" show-overflow></vxe-column>
        <vxe-column field="login" title="登录状态">
          <template #default="{ row }">
            <el-tag v-if="row.login == '1'" type="success">已登录</el-tag>
            <el-tag v-else type="danger">未登录</el-tag>
          </template>
        </vxe-column>
        <vxe-column field="created_at" title="创建时间"></vxe-column>
        <vxe-column title="操作" width="160">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editUser(row)">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>修改</span>
            </el-button>
            <el-button type="primary" size="small" @click="delUser(row)">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>删除</span>
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <div style="display: flex; justify-content: center; margin-top: 24px">
        <el-pagination
          @update:current-page="handlePageChange"
          :default-page-size="10"
          :total="total"
          size="small"
          background
          layout="prev, pager, next"
          class="mt-4"
        />
      </div>
    </el-card>

    <!-- 用户对话框（新增/修改共用） -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="旺旺名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入旺旺名称"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="form.pwd" type="text" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">{{ dialogButtonText }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, toValue } from 'vue'
import { ElMessage } from 'element-plus'
import { useConfigStore } from '../stores/config'

// 获取配置store
const configStore = useConfigStore()
console.log(configStore.config)
const test = () => {
  window.electron.ipcRenderer.send('ping', 'hello')
  ElMessage({ message: '发送成功', type: 'success' })
}
const test1 = () => {
  window.electron.ipcRenderer.send('open-tb-address', 'hello')
}
let page = ref(1)
let total = ref(0)
const handlePageChange = async (e) => {
  page.value = e
  await getUserData()
}
let tableData = ref([])
onMounted(async () => {
  getUserData()
})
const getUserData = async () => {
  let data = await window.electronAPI.getUsers(page.value, 10, '')
  tableData.value = data.users
  total.value = data.total
}
const tableRef = ref(null)
const selectedData = ref([])
// 用户对话框相关变量
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const dialogButtonText = ref('确认')
const formRef = ref(null)
const form = ref({
  id: '',
  name: '',
  pwd: ''
})
// 表单验证规则
const rules = ref({
  name: [
    { required: true, message: '请输入旺旺名称', trigger: 'blur' },
    { min: 2, max: 20, message: '旺旺名称长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
  ]
})

// 打开新增用户对话框
const addUser = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogTitle.value = '新增用户'
  dialogButtonText.value = '确认'
  dialogVisible.value = true
}

// 打开编辑用户对话框
const editUser = (row) => {
  dialogTitle.value = '修改用户'
  dialogButtonText.value = '更新'
  // 复制行数据到表单
  form.value = { ...row }
  console.log('编辑的用户数据:', form.value)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 这里可以添加提交数据到后端的逻辑
      console.log('提交的用户数据:', form.value)

      // 模拟提交成功
      if (dialogTitle.value === '新增用户') {
        await window.electronAPI.addUser(form.value.name, form.value.pwd)
        getUserData()
        ElMessage.success('用户添加成功')
      } else {
        await window.electronAPI.editUser(form.value.name, form.value.pwd, form.value.id)
        getUserData()
        ElMessage.success('用户更新成功')
      }
      dialogVisible.value = false
    }
  })
}

const getSelectedData = () => {
  if (tableRef.value) {
    const records = tableRef.value.getCheckboxRecords()
    selectedData.value = records
  }
}

// 下载店铺导入模板
const downTemplate = () => {
  window.electronAPI
    .downTemplate()
    .then(() => {
      ElMessage.success('模板下载成功')
    })
    .catch((err) => {
      ElMessage.error(`模板下载失败: ${err.message}`)
    })
}

// 导入店铺数据
const importShop = () => {
  window.electronAPI
    .importShop()
    .then((data) => {
      if (data && data.length > 0) {
        ElMessage.success(`成功导入 ${data.length} 条店铺数据`)
      } else {
        ElMessage.info('没有找到可导入的数据')
      }
      getUserData()
    })
    .catch((err) => {
      ElMessage.error(`导入失败: ${err.message}`)
    })
}

const loginShop = () => {
  getSelectedData()
  if (selectedData.value.length === 0) {
    ElMessage({
      message: '请选择要登录的店铺',
      offset: 300,
      type: 'error'
    })
    return
  }
  const loginData = selectedData.value.filter((x) => x.login === 0)
  console.log('开始登录店铺', toValue(loginData))
  window.electron.ipcRenderer.send('open-more-window', JSON.stringify(loginData))
}
</script>

<style scoped></style>
